//
//  BDPanOauthManager.m
//  APaaS
//
//  Created by luochao04 on 2022/6/15.
//

#import "BDPanOauthManager.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "HYRequestBaseHelper.h"
#import <HYUtls/CommUtls+DeviceInfo.h>
#import <NSString+MJExtension.h>
#if DEBUG
static NSString *kBDPanOauthAppID = @"38556990";//@"26459887";
static NSString *kBDPanOauthAppkey = @"ind9tn3v8NC1Sb2eQSSyKuxGtGANpoGU";//@"jKkBDMKYQlunDWQggnPRB5AU6oAF2Gk2";
static NSString *kBDPanOauthrSecretKey = @"7YAMwy1nj41kY6V6ceK9g2Hzq9K9Xjme";//@"pVBN3yLgIofxoYZsHstBzHB3Spt5gKBK";
static NSString *kUserIdentifier = @"VPlayer";
#else
static NSString *kBDPanOauthAppID = @"26441369";
static NSString *kBDPanOauthAppkey = @"idiOyHE1i8qTTjilLTr3VZi9GcGF8Lfj";
static NSString *kBDPanOauthrSecretKey = @"sIcUzvHISrsdyI5YZ6Nh79pOlHErceMP";
#endif

static NSString *kBDPanOauthrRedirectURI = @"oob";//@"oob";//@"https://passport.baidu.com";
static NSString *kBDPanOauthScope = @"basic,netdisk";


static NSString *kBDPanOauthAccessToken = @"kBDPanOauthAccessToken";
static NSString *kBDPanOauthRefreshToken = @"kBDPanOauthRefreshToken";
static NSString *kBDPanUserInfoVIP = @"kBDPanUserInfoVIP";

@interface BDPanOauthManager ()

@property (nonatomic, copy) NSString *oauthCode;

@property (nonatomic, copy) BDPanOauthCompletion completion;
@property (nonatomic, strong) dispatch_queue_t requestQueue;

@end

@implementation BDPanOauthManager

+ (instancetype)manager
{
    static BDPanOauthManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

// 退出网盘 重置SDK 清空.accessToken refreshToken
- (void)quitBDpan:(LoginOutBDpan)loginOut
{
    [self disableOauthInfo];
    [HYHub showMessage:NSLocalizedString(@"成功退出当前账号", nil)];
    if(loginOut){
        loginOut();
    }
}

- (NSInteger)appId
{
    return [kBDPanOauthAppID integerValue];
}

- (NSString *)accessToken
{
    NSString *ak = [[NSUserDefaults standardUserDefaults] objectForKey:kBDPanOauthAccessToken];
    return ak;
}
- (void)setAccessToken:(NSString *)accessToken
{
    [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:kBDPanOauthAccessToken];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self getUserInfo:^(NSString * _Nonnull errorStr) {
        
    }];
}

- (NSString *)refreshToken
{
    NSString *ak = [[NSUserDefaults standardUserDefaults] objectForKey:kBDPanOauthRefreshToken];
    return ak;
}
- (NSString *)userVip
{
    NSString *vip = [[NSUserDefaults standardUserDefaults] objectForKey:kBDPanUserInfoVIP];
    return vip;
}
- (void)disableOauthInfo
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kBDPanOauthAccessToken];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kBDPanUserInfoVIP];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)BDPanOauthAppID
{
    return kBDPanOauthAppID;
}

- (NSString *)BDPanOauthAppkey
{
    return kBDPanOauthAppkey;
}

- (NSString *)BDPanOauthrSecretKey
{
    return kBDPanOauthrSecretKey;
}

- (NSString *)BDPanOauthrRedirectURI
{
    return kBDPanOauthrRedirectURI;
}

- (NSString *)BDPanOauthScope
{
    return kBDPanOauthScope;
}

- (void)searchFids:(id )fid bDFileInfo:(BDFileInfo)bDFileInfo
{
    NSString *fids = @"";
    if ([fid isKindOfClass:[NSString class]]) {
        fids = fid;
    }
    if ([fid isKindOfClass:[NSArray class]]) {
        fids = [(NSArray *)fid componentsJoinedByString:@","];
    }
    NSString *access_token = self.accessToken;
    NSString *needmedia = @"1";
    NSString *extra = @"1";
    NSString *thumb = @"1";
    NSString *dlink = @"1";
    NSString *url = [NSString stringWithFormat:@"http://pan.baidu.com/rest/2.0/xpan/multimedia?method=filemetas&access_token=%@&fsids=[%@]&thumb=%@&dlink=%@&extra=%@&needmedia=%@",access_token,fids,thumb,dlink,extra,needmedia];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"pan.baidu.com" forKey:@"User-Agent"];
    [HYRequestBaseHelper GET:url parameters:nil headers:dic success:^(id responseObject) {
        CLog(@"responseObject -- %@",responseObject);
        if(bDFileInfo){
            bDFileInfo(responseObject);
        }
    } failure:^(NSError *error, NSString *errorStr) {
        [HYHub showMessage:NSLocalizedString(@"获取数据失败", nil)];
    }];
}
- (void)subList:(NSString *)path bDFileInfo:(BDFileInfo)bDFileInfo
{
    //中文转unicode
    NSString *pathString = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *access_token = self.accessToken;
    NSString *web = @"1";
    NSString *recursion = @"0";
    NSString *start = @"0";
    NSString *url = @"";
    NSString *folder = @"0";
    
    if ([path isEqualToString:@"/"]) {
        url = [NSString stringWithFormat:@"https://pan.baidu.com/rest/2.0/xpan/file?method=list&dir=%@&access_token=%@&order=time&start=%@&web=%@&folder=%@&desc=1",path,self.accessToken,start,web,folder];
    }else{
        url = [NSString stringWithFormat:@"http://pan.baidu.com/rest/2.0/xpan/multimedia?method=listall&path=%@&access_token=%@&web=%@&recursion=%@&start=%@",pathString,access_token,web,recursion,start];
    }
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"pan.baidu.com" forKey:@"User-Agent"];
    [HYHub loadMessage:NSLocalizedString(@"加载数据中", nil)];
    [HYRequestBaseHelper GET:url parameters:nil headers:dic success:^(id responseObject) {
        [HYHub dismiss];
        if(bDFileInfo){
            bDFileInfo(responseObject);
        }
    } failure:^(NSError *error, NSString *errorStr) {
        [HYHub showMessage:NSLocalizedString(@"获取数据失败", nil)];
    }];
}

- (void)getUserInfo:(UserInfoErrorCodeString)errorCodeStr
{
    NSString *url = [NSString stringWithFormat:@"https://pan.baidu.com/rest/2.0/xpan/nas?access_token=%@&method=uinfo",self.accessToken];
    NSDictionary *dic = @{@"Host":@"pan.baidu.com"};
    [HYRequestBaseHelper GET:url parameters:nil headers:dic success:^(id responseObject) {
        CLog(@"%@",responseObject);
        if([responseObject isKindOfClass:[NSDictionary class]]){
            NSString *vip = [NSString stringWithFormat:@"%@",responseObject[@"vip_type"]];
            [self saveUserVIP:vip];
            !errorCodeStr ? :errorCodeStr(@"");
        }
    } failure:^(NSError *error, NSString *errorStr) {
        CLog(@"errorStr-----%@",errorStr);
        if (errorStr.length) {
           !errorCodeStr ? :errorCodeStr(errorStr);
        }
    }];
}

- (void)saveUserVIP:(NSString *)vip
{
    CLog(@"%@",vip);
    [[NSUserDefaults standardUserDefaults] setObject:vip forKey:kBDPanUserInfoVIP];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)fetchVideoInfoWithModel:(HYBDPanFileModelList *)model completion:(BDFileInfo)completion
{
    NSString *access_token = self.accessToken;
    NSString *path = [model.path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *type = @"M3U8_AUTO_480";
    NSString *url = [NSString stringWithFormat:@"http://pan.baidu.com/rest/2.0/xpan/file?method=streaming&access_token=%@&path=%@&type=%@",access_token,path,type];
    NSString *systemName = [CommUtls getDeviceName];
    NSString *systemVersion = [CommUtls getSystemVersion];
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [NSString stringWithFormat:@"%@",infoDic[@"CFBundleShortVersionString"]];
    NSString *userStr = [NSString stringWithFormat:@"xpanvideo;VPlayer;%@;%@;%@;ts",currentVersion,systemName,systemVersion];
    NSDictionary *dic = @{@"User-Agent":userStr,@"Host":@"pan.baidu.com"};
    @weakify(self);
    [HYRequestBaseHelper GET:url parameters:nil headers:dic success:^(id responseObject) {
        @strongify(self);
        CLog(@"responseObjectsuccess -- %@",responseObject);
        ///超级会员仅请求一次直接返回URL 进行播放
        if ([self.userVip isEqualToString:@"2"]) {
            if (completion) {
                completion(url);
            }
            return;
        }
        if([responseObject isKindOfClass:[NSDictionary class]]){
            NSInteger ltime = [responseObject[@"ltime"] integerValue];
            NSString *token = responseObject[@"adToken"];
            NSString *adToken = [token stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"ABC-_~.!*'();: $,/?%#[]"]];
            if(adToken){
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(ltime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self fetchVideoPlayrUrlWithRequestUrl:[url stringByAppendingFormat:@"&adToken=%@",adToken]
                                                completion:completion];
                });
            }
        }
    } failure:^(NSError *error, NSString *errorStr) {
        CLog(@"responseObjecterror -- %@",errorStr);
    }];
    
}

- (void)fetchVideoPlayrUrlWithRequestUrl:(NSString *)requestUrl
                              completion:(BDFileInfo)completion
{
    NSString *systemName = [CommUtls getDeviceName];
    NSString *systemVersion = [CommUtls getSystemVersion];
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [NSString stringWithFormat:@"%@",infoDic[@"CFBundleShortVersionString"]];
    NSString *userStr = [NSString stringWithFormat:@"xpanvideo;VPlayer;%@;%@;%@;ts",currentVersion,systemName,systemVersion];
    NSDictionary *dic = @{@"User-Agent":userStr,@"Host":@"pan.baidu.com"};
    [HYRequestBaseHelper GET:requestUrl parameters:nil headers:dic success:^(id responseObject) {
        CLog(@"responseObjectsuccess2 -- %@",responseObject);
        if(completion){
            completion(requestUrl);
        }
    } failure:^(NSError *error, NSString *errorStr) {
        CLog(@"responseObjecterror2 -- %@",errorStr);
        if(completion){
            completion(requestUrl);
        }
    }];
}
@end
